import axios from "axios";
let MobileDetect = require('mobile-detect')

import { VUE_APP_API_URL } from "@utils/index";

Array.prototype.contains = (needle) => {
    for (let i in this) {
        if (this[i].indexOf(needle) > 0)
            return i;
    }
    return -1;
}
//获取设备手机型号
var device_type = navigator.userAgent;//获取userAgent信息  
var md = new MobileDetect(device_type);//初始化mobile-detect  
var os = md.os();//获取系统  
var model = "";
var phone = md.phone() || "iPhone"
if (os == "iOS") {//ios系统的处理  
    os = md.os() + md.version("iPhone");
    model = md.mobile();
} else if (os == "AndroidOS") {//Android系统的处理  
    os = md.os() + md.version("Android");
    var sss = device_type.split(";");
    var i = sss.contains("Build/");
    if (i > -1) {
        model = sss[i].substring(0, sss[i].indexOf("Build/"));
    } else {
        model = 'default'
    }
}

//请求初始化参数
const instance = axios.create({
    baseURL: VUE_APP_API_URL || `${location.origin}/api`,
    timeout: 20000,
    post: {
        'Content-Type': 'application/json'
    },
    isLogin: false
});
axios.interceptors.request.use = instance.interceptors.request.use
instance.interceptors.request.use(config => {
    console.log(config)
    config.headers.language = 'zh_CN'
    config.headers.Authorization = ''
    config.headers['X-IM-Common'] = `{"androidId":"","brand":"${phone}","channel":"","imei":"ffffffff-c5f4-4c55-ffff-ffffef05ac4a","mac":"","model":"${model}","oaid":"","os":"Android","os_version":"11","pkg":"com.weiju.imchat.debug","smid":"","versionCode":62}`
    if (localStorage.getItem('token') && config.isLogin) {
        config.headers.Authorization = `${localStorage.getItem('token')}`
        // .replace(/(^\")|(\"$)/g, '')
    }
    return config
}, err => {
    return Promise.reject(err)
})
// axios拦截响应
instance.interceptors.response.use(response => {
    if (response.data.code == 401) {
        location.href = '/login'
    }
    return Promise.resolve(response.data)
}, err => {
    return Promise.reject(err)
})

export default instance;
